--- 模块功能：电源管理
-- @author zgt
-- @module create
-- @license MIT
-- @copyright zgt
-- @release 2022-1-6
require "net"
require "pins"
module(..., package.seeall)

local prefix = "power"
-- 设置LCD驱动电压
pmd.ldoset(15, pmd.LDO_VLCD)
pmd.ldoset(15, pmd.LDO_VMMC)
pmd.ldoset(15, pmd.LDO_VSIM1)

local p_master = pins.setup(30, 0)
local p_ready =  pins.setup(4, 0)
local p_resw1 = pins.setup(5, 0) -- 继电器1
local p_resw2 = pins.setup(19, 0) -- 继电器2
local p_dc_out = pins.setup(28, 0) -- dc_out
local p_dc_boost = pins.setup(17, 0) -- 升压
local p_blue = pins.setup(22, 0) -- 蓝灯
local p_wdi = pins.setup(17, 0) -- 看门狗
-- adc
local adc_vbat_id = 2
local adc_ir = 3
-- 关闭总电源
function closeMaster()
    p_master(0)
end
-- 锁定主电源
function openMasterLock()
    p_master(1)
end
-- 打开输出 vbat
function openVout()
    p_dc_out(1)
end
function closeVout()
    p_dc_out(0)
end
-- 打开24V输出
function openBoost()
    p_dc_boost(1)
end
function closeBoost()
    p_dc_boost(0)
end
-- 打开继电器1
function openSW1()
    p_resw1(1)
end
function closeSW1()
    p_resw1(0)
end
-- 打开继电器2
function openSW2()
    p_resw2(1)
end
function closeSW2()
    p_resw2(0)
end

-- 电压adc通道电压读取
-- @id adc通道id 2:总电源
function getADC(id)
    adc.open(id)
    local adcValue, voltValue = adc.read(id)
    -- log.warn("power->",string.format("adc= %d,adcVal = %d,voltVal= %d",id,adcValue,voltValue))
    adc.close(id)
    if voltValue ~= 0xFFFF  then return voltValue end
    return 0
end
function getVbat( )
    return getADC(adc_vbat_id) * 11 / 1000 
end
function getVI( )
    return getADC(adc_ir) * 11 / 1000 
end

sys.taskInit(function()
    while true do
        p_master(1)
        --p_dc_out(0)
        --p_dc_boost(0)
        p_resw1(1)
        --p_resw2(0)
        p_ready(1)
        p_blue(1)
        p_wdi(1)
        sys.wait(2000)
        --p_master(1)
        --p_dc_out(1)
        --p_dc_boost(1)
        p_resw1(0)
        --p_resw2(1)
        p_ready(0)
        p_blue(0)
        p_wdi(0)
        sys.wait(2000)
        p_ready(1)
        p_blue(1)
        p_resw1(1)
        p_wdi(1)
        sys.wait(120000)
        p_ready(0)
        p_blue(0)
        p_resw1(0)
        sys.wait(400000)
    end
end)